import _ from "lodash";
import {useBoolean} from "ahooks";
import {Button, Form, Modal, Table, message, notification} from "antd";
import {
    columnsIsBind,
    columnsPositionId,
    columnsPositionSubId,
    columnsSetting,
    getColumnsId,
} from "@/components/Columns";
import {InputFormItem, SelectFormItem} from "@/components/common/form/formItem";
import useList from "@/hooks/useList";
import {ResProps, adAdd, adEdit, adFinApplyingUser, adFindBindUser, adGetList} from "@/api";
import {useState} from "react";

const defaultValue = {
    mediaName: "番茄有惠券",
    mediaId: "2976700403",
    commissionRate: 0.7,
};

const AdvertList = () => {
    const [form] = Form.useForm();
    const [open, {setFalse, setTrue}] = useBoolean(false);
    const [type, setType] = useState<"add" | "edit" | "addUser">("add"); //add 添加推广位  edit 编辑推广位 addUser添加用户

    const {data: user} = useList({api: adFinApplyingUser});
    const {data: bindUser} = useList({api: adFindBindUser});

    const {data, refresh} = useList({
        api: adGetList,
    });

    const handleCreate = () => {
        setTrue();
        form.setFieldsValue(defaultValue);
    };

    const handleEdit = (row: any) => {
        setTrue();
        setType("edit");
        const newData: any = _.assign(row, defaultValue);
        const item: any = _.find(bindUser.list, ({openId}: any) => openId === newData.openId);
        let formVal = {};
        if (item) {
            formVal = _.set(newData, "nickName", item.nickName);
        } else {
            formVal = _.set(newData, "nickName", "暂未绑定用户");
        }
        form.setFieldsValue(formVal);
    };

    const handleUnBind = row => {
        const newData = _.set(row, "openId", "");
        adEdit(newData);
    };
    const handleBind = row => {
        setTrue();
        setType("addUser");
        form.setFieldsValue(row);
    };

    const columns = [
        getColumnsId(data),
        {title: "推广位名称", dataIndex: "positionName", key: "positionName"},
        {title: "媒体名称", dataIndex: "mediaName", key: "mediaName"},
        // columnsCommissionRate,
        columnsPositionId,
        columnsPositionSubId,
        columnsIsBind,
        {
            ...columnsSetting,
            width: 200,
            render: (_: any, row: any) => (
                <div className="flr">
                    <Button type="primary" size="small" onClick={() => handleEdit(row)}>
                        编辑
                    </Button>
                    {row.openId ? (
                        <Button danger type="primary" disabled size="small" onClick={() => handleUnBind(row)}>
                            解绑
                        </Button>
                    ) : (
                        <Button type="primary" size="small" onClick={() => handleBind(row)}>
                            绑定用户
                        </Button>
                    )}
                </div>
            ),
        },
    ];

    const handleClose = () => {
        form.resetFields();
        setFalse();
        setType("add");
    };
    const handleSubmit = async () => {
        form.validateFields().then(async info => {
            try {
                let data = {};
                if (type === "add") {
                    data = _.omit(_.cloneDeep(info), "uuid");
                } else if (type === "edit") {
                    if (info.nickName) {
                        data = _.omit(_.cloneDeep(info), "nickName");
                    }
                } else if (type === "addUser") {
                    data = info;
                }
                const res: ResProps = await adAdd(data);
                if (res.success) {
                    refresh();
                    handleClose();
                    message.success({content: "推广位添加成功"});
                }
            } catch (err) {
                notification.info({message: "创建推广位失败", description: JSON.stringify(err)});
            }
        });
    };

    return (
        <div className="components-list">
            <div className="fl mb20">
                <Button type="primary" onClick={handleCreate}>
                    添加推广位
                </Button>
            </div>
            <Table rowKey={row => JSON.stringify(row)} dataSource={data.list} columns={columns} />

            <Modal
                title={type === "add" ? "创建推广位" : type === "edit" ? "编辑推广位" : "绑定用户"}
                bodyStyle={{paddingTop: 20}}
                className="user-list-modal"
                open={open}
                onOk={handleSubmit}
                onCancel={handleClose}
            >
                <Form form={form} labelCol={{span: 6}}>
                    <InputFormItem name="uuid" hidden />
                    <InputFormItem required name="positionName" label="推广位名称" />
                    <InputFormItem required name="positionId" label="推广位ID" />
                    {type === "add" || type === "addUser" ? (
                        <SelectFormItem
                            name="openId"
                            label="绑定用户"
                            options={_.map(user.list, ({nickName, openId}) => ({label: nickName, value: openId}))}
                        />
                    ) : (
                        <>
                            <InputFormItem required name="openId" hidden label="绑定用户" />
                            <InputFormItem required name="nickName" disabled label="用户名称" />
                        </>
                    )}

                    <InputFormItem
                        name="commissionRate"
                        label="佣金比例"
                        tooltip="目前用户分成7/3"
                        initialValue={0.7}
                        disabled
                    />

                    <InputFormItem
                        name="mediaName"
                        label="媒体名称"
                        disabled
                        initialValue="番茄有惠券"
                        value="番茄有惠券"
                    />
                    <InputFormItem
                        name="mediaId"
                        label="媒体ID"
                        disabled
                        initialValue="2976700403"
                        value="2976700403"
                    />
                </Form>
            </Modal>
        </div>
    );
};

export default AdvertList;
